﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
using System.Web;
using System.Security.Cryptography;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Net.Mail;

namespace Ultility
{
    public class LibraryCommon
    {
        private static SqlConnection _connection;
        private static string _connectionString = ConfigurationManager.ConnectionStrings["WebAQConnectionString"].ConnectionString;


        public static DataSet ExcuteDatasetStore(string storename)
        {
            _connection = new SqlConnection(_connectionString);
            DataSet ds = new DataSet();
            SqlCommand com = new SqlCommand(storename, _connection);
            com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adap = new SqlDataAdapter(com);
            adap.Fill(ds);
            return ds;

        }
        public static DataSet ExcuteDatasetStore(string storename, SqlParameter[] prams)
        {
            _connection = new SqlConnection(_connectionString);
            DataSet ds = new DataSet();
            SqlCommand com = new SqlCommand(storename, _connection);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddRange(prams);
            SqlDataAdapter adap = new SqlDataAdapter(com);
            adap.Fill(ds);
            return ds;

        }
        public static void ExcuteStore(string storename)
        {
            _connection = new SqlConnection(_connectionString);

            SqlCommand com = new SqlCommand(storename, _connection);
            com.CommandType = CommandType.StoredProcedure;
            _connection.Open();
            com.ExecuteNonQuery();
            _connection.Close();


        }
        public static void ExcuteStore(string storename, SqlParameter[] prams)
        {
            _connection = new SqlConnection(_connectionString);

            SqlCommand com = new SqlCommand(storename, _connection);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddRange(prams);
            _connection.Open();
            com.ExecuteNonQuery();
            _connection.Close();
        }
    }

    public class tool
    {
        public void SetMetaData(Page page, string title, string description, string keyword)
        {
            if (!string.IsNullOrEmpty(title))
            {
                page.Title = title;


            }

            if (!string.IsNullOrEmpty(description) || !string.IsNullOrEmpty(keyword))
            {

                HtmlMeta keywords = new HtmlMeta();
                keywords.Name = keyword;
                keywords.Content = description;

                page.Header.Controls.Add(keywords);

            }

        }

        public bool check(CheckBox ck)
        {
            if (ck.Checked == true)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        public void PrintWebControl(Control ctrl)
        {
            PrintWebControls(ctrl, "");
        }

        public void PrintWebControls(Control ctrl, string Script)
        {
            StringWriter stringWrite = new StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
            if (ctrl is WebControl)
            {
                Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
            }
            Page pg = new Page();
            pg.EnableEventValidation = false;
            if (Script != string.Empty)
            {
                pg.ClientScript.RegisterStartupScript(pg.GetType(), Script + "PrintJavaScript", Script);
            }
            HtmlForm frm = new HtmlForm();
            pg.Controls.Add(frm);
            frm.Attributes.Add("runat", "server");
            frm.Controls.Add(ctrl);
            pg.DesignerInitialize();
            pg.RenderControl(htmlWrite);
            string strHTML = stringWrite.ToString();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(strHTML);
            HttpContext.Current.Response.Write("<script>window.print();window.close();</script>");
            HttpContext.Current.Response.End();
        }

        #region ENCRYPT PASS
        /// <summary>
        /// Giải mã
        /// </summary>
        /// <param name="cleanString">Chuỗi cần giải mã</param>
        /// <returns>Chuỗi sau khi giải mã</returns>
        public string Encrypt(string cleanString)
        {
            Byte[] clearBytes = new System.Text.UnicodeEncoding().GetBytes(cleanString);
            Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
            hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(hashedBytes);
            return BitConverter.ToString(hashedBytes);
        }
        #endregion
        #region CutMark
        /// <summary>
        /// Ham cat chuoi co dau thanh ko dau
        /// </summary>
        /// <param name="StringInput"></param>
        /// <returns></returns>
        /// 
        public string CutMark(string StringInput)
        {
            if (Mang.GetValue(0, 0) == null) GetArray();
            string temp1, temp2;
            byte i, j;
            temp1 = StringInput;
            for (j = 0; j <= 13; j++)
            {
                for (i = 1; i < 17; i++)
                {
                    temp2 = temp1.Replace(Mang.GetValue(j, i).ToString(), Mang.GetValue(j, 0).ToString());
                    temp1 = temp2;
                }
            }
            return temp1;
        }

        public Array Mang = Array.CreateInstance(typeof(string), 14, 17);

        public void GetArray()
        {
            //tao mang
            Byte i, j;
            string str;
            string Thga, Thge, Thgo, Thgu, Thgi, Thgd, Thgy;
            string HoaA, HoaE, HoaO, HoaU, HoaI, HoaD, HoaY;
            str = "aAeEoOuUiIdDyY";
            Thga = "ăâàảãạáằẳẵặắầẩẫậấ";
            HoaA = "ĂÂÀẢÃẠÁẰẲẴẶẮẦẨẪẬẤ";
            Thge = "êèẻẽẹéềểễệếeeeeee";
            HoaE = "ÊÈẺẼẸÉỀỂỄỆẾEEEEEE";
            Thgo = "ôơòỏõọóồổỗộốờởỡợớ";
            HoaO = "ÔƠÒỎÕỌÓỒỔỖỘỐỜỞỠỢỚ";
            Thgu = "ưùủũụúừửữựứuuuuuu";
            HoaU = "ƯÙỦŨỤÚỪỬỮỰỨUUUUUU";
            Thgi = "ìỉĩịíiiiiiiiiiiii";
            HoaI = "ÌỈĨỊÍIIIIIIIIIIII";
            Thgd = "đđđđđđđđđđđđđđđđđ";
            HoaD = "ĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐĐ";
            Thgy = "ỳỷỹỵýyyyyyyyyyyyy";
            HoaY = "ỲỶỸỴÝYYYYYYYYYYYY";
            //Nạp vào trong Mang các ký tự
            //Nạp vào từng đầu hàng các ký tự không dấu
            //Nạp vào cột dầu tiên
            for (i = 0; i <= 13; i++)
            {
                Mang.SetValue(str.Substring(i, 1), i, 0);
            }
            //Nap vào tung ô các ký tu có dau
            for (j = 1; j < 17; j++)
            {
                for (i = 1; i < 17; i++)
                {
                    //Nap tung ký tu trong chuoi Thga vào tung ô trong hàng 0
                    Mang.SetValue(Thga.Substring(i - 1, 1), 0, i);
                    Mang.SetValue(HoaA.Substring(i - 1, 1), 1, i);
                    Mang.SetValue(Thge.Substring(i - 1, 1), 2, i);
                    Mang.SetValue(HoaE.Substring(i - 1, 1), 3, i);
                    Mang.SetValue(Thgo.Substring(i - 1, 1), 4, i);
                    Mang.SetValue(HoaO.Substring(i - 1, 1), 5, i);
                    Mang.SetValue(Thgu.Substring(i - 1, 1), 6, i);
                    Mang.SetValue(HoaU.Substring(i - 1, 1), 7, i);
                    Mang.SetValue(Thgi.Substring(i - 1, 1), 8, i);
                    Mang.SetValue(HoaI.Substring(i - 1, 1), 9, i);
                    Mang.SetValue(Thgd.Substring(i - 1, 1), 10, i);
                    Mang.SetValue(HoaD.Substring(i - 1, 1), 11, i);
                    Mang.SetValue(Thgy.Substring(i - 1, 1), 12, i);
                    Mang.SetValue(HoaY.Substring(i - 1, 1), 13, i);
                }
            }
        }
        #endregion
        #region READFILE
        /// <summary>
        /// Đọc file 
        /// </summary>
        /// <param name="fileName">Đường dẫn file cần đọc</param>
        /// <returns>Nội dung file</returns>
        public string readTextFile(string fileName)
        {
            string returnVal = "";
            try
            {
                StreamReader fReader = new StreamReader(fileName, System.Text.Encoding.Unicode);
                returnVal = fReader.ReadToEnd();
                fReader.Close();
            }
            catch (Exception err)
            {
                returnVal = err.Message;
            }
            return returnVal;
        }
        #endregion

        #region ERROR
        /// <summary>
        /// Ghi thông báo lỗi vào file
        /// </summary>
        /// <param name="ex">Nội dung lỗi</param>
        /// <returns>True:Nếu ghi file được,False:Không ghi file được</returns>
        public static bool ErrorReturn(string ex)
        {
            try
            {
                HttpContext context = HttpContext.Current;
                StreamReader rd = new StreamReader(context.Server.MapPath(@"~\err\tester.txt"));
                string strtext = rd.ReadToEnd();
                rd.Close();
                strtext += "\r\n" + DateTime.Now.ToString() + "\r\n" + ex;
                StreamWriter wt = new StreamWriter(context.Server.MapPath(@"~\err\tester.txt"));
                wt.Write(strtext);
                wt.Close();
                return true;
            }
            catch { return false; }

            //Response.Redirect(@"~/Error/Error.aspx");
        }
        #endregion
        public static bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);

                // Writes a block of bytes to this stream using data from a byte array.
                _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

                // close file stream
                _FileStream.Close();

                return true;
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            // error occured, return false
            return false;
        }
        #region CHECK_EMAIL_FORMAT
        /// <summary>
        /// Kiểm tra định dạng Email
        /// </summary>
        /// <param name="Email">Email truyền vào</param>
        /// <returns>True:Nếu email đó đúng định dạng,False:Không đúng định dạng</returns>
        public static bool CheckEmailFormat(string Email)
        {
            if (Email.IndexOf("!") != -1) return false;
            if (Email.IndexOf("~") != -1) return false;
            if (Email.IndexOf("#") != -1) return false;
            if (Email.IndexOf("$") != -1) return false;
            if (Email.IndexOf("%") != -1) return false;
            if (Email.IndexOf("^") != -1) return false;
            if (Email.IndexOf("&") != -1) return false;
            if (Email.IndexOf("*") != -1) return false;
            if (Email.IndexOf("(") != -1) return false;
            if (Email.IndexOf(")") != -1) return false;
            if (Email.IndexOf("<") != -1) return false;
            if (Email.IndexOf(">") != -1) return false;
            if (Email.IndexOf("+") != -1) return false;
            if (Email.IndexOf("=") != -1) return false;
            if (Email.IndexOf(":") != -1) return false;
            if (Email.IndexOf("\"") != -1) return false;
            if (Email.IndexOf(";") != -1) return false;
            if (Email.IndexOf("'") != -1) return false;
            if (Email.IndexOf("{") != -1) return false;
            if (Email.IndexOf("}") != -1) return false;
            if (Email.IndexOf("[") != -1) return false;
            if (Email.IndexOf("]") != -1) return false;
            if (Email.IndexOf(",") != -1) return false;
            if (Email.IndexOf("?") != -1) return false;
            if (Email.IndexOf("/") != -1) return false;
            if (Email.IndexOf("\\") != -1) return false;
            if (Email.IndexOf("|") != -1) return false;
            if (Email.IndexOf("`") != -1) return false;
            string[] tmp; tmp = Email.Split('@');
            if (tmp.Length != 2) return false;
            int posA = Email.IndexOf("@");
            if (posA == 0 || posA == Email.Length - 1)
                return false;
            if (posA > Email.LastIndexOf(".")) return false;
            if (Email.Substring(0, 1) == "." || Email.Substring(Email.Length - 1, 1) == "." || Email.Substring(posA + 1, 1) == "." || Email.Substring(posA - 1, 1) == ".") return false;
            return true;
        }
        #endregion
        /// <summary>
        /// Chuyển đổi image tới byte[]
        /// </summary>
        /// <param name="imageIn"></param>
        /// <returns></returns>
        public static byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
        /// <summary>
        /// Chuyển đổi byte[] sang image
        /// </summary>
        /// <param name="byteArrayIn"></param>
        /// <returns></returns>
        public static System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
        {

            MemoryStream ms = new MemoryStream(byteArrayIn);
            System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);

            return returnImage;
        }


        public static byte[] CreateThumbnail(byte[] PassedImage, int LargestSide)
        {
            byte[] ReturnedThumbnail;

            using (MemoryStream StartMemoryStream = new MemoryStream(),
                                NewMemoryStream = new MemoryStream())
            {
                // write the string to the stream  
                StartMemoryStream.Write(PassedImage, 0, PassedImage.Length);

                // create the start Bitmap from the MemoryStream that contains the image  
                Bitmap startBitmap = new Bitmap(StartMemoryStream);

                // set thumbnail height and width proportional to the original image.  
                int newHeight;
                int newWidth;
                double HW_ratio;
                if (startBitmap.Height > startBitmap.Width)
                {
                    newHeight = LargestSide;
                    HW_ratio = (double)((double)LargestSide / (double)startBitmap.Height);
                    newWidth = (int)(HW_ratio * (double)startBitmap.Width);
                }
                else
                {
                    newWidth = LargestSide;
                    HW_ratio = (double)((double)LargestSide / (double)startBitmap.Width);
                    newHeight = (int)(HW_ratio * (double)startBitmap.Height);
                }

                // create a new Bitmap with dimensions for the thumbnail.  
                Bitmap newBitmap = new Bitmap(newWidth, newHeight);

                // Copy the image from the START Bitmap into the NEW Bitmap.  
                // This will create a thumnail size of the same image.  
                newBitmap = ResizeImage(startBitmap, newWidth, newHeight);

                // Save this image to the specified stream in the specified format.  
                newBitmap.Save(NewMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                // Fill the byte[] for the thumbnail from the new MemoryStream.  
                ReturnedThumbnail = NewMemoryStream.ToArray();
            }

            // return the resized image as a string of bytes.  
            return ReturnedThumbnail;
        }
        public static Bitmap ResizeImage(Bitmap image, int width, int height)
        {
            Bitmap resizedImage = new Bitmap(width, height);
            using (Graphics gfx = Graphics.FromImage(resizedImage))
            {
                gfx.DrawImage(image, new Rectangle(0, 0, width, height),
                    new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
            }
            return resizedImage;
        }
        public static bool IsNumericRegEx(string str)
        {
            str = str.Trim();
            return (Regex.IsMatch(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$"));
        }
        public bool Sendmailforgetpass(string From, string Subject, string toEmail, string Content)
        {
            try
            {

                if (CheckEmailFormat(From) && CheckEmailFormat(toEmail))
                {
                    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

                    mail.From = new MailAddress(From);
                    mail.Subject = Subject;
                    mail.To.Add(toEmail);
                    mail.IsBodyHtml = true;
                    mail.BodyEncoding = System.Text.Encoding.UTF8;
                    mail.IsBodyHtml = true;
                    mail.Body = Content;
                    SmtpClient client = new SmtpClient();
                    client.Send(mail);
                }
                return true;
            }
            catch
            {

                return false;
            }
        }
        #region fogetpass
        public string CreateLostPassword(int PasswordLength)
        {
            string _allowedChars = "abcdefghijk0123456789mnopqrstuvwxyz";
            Random randNum = new Random();
            char[] chars = new char[PasswordLength];
            int allowedCharCount = _allowedChars.Length;

            for (int i = 0; i < PasswordLength; i++)
            {
                chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
            }
            return new string(chars);
        }


        #endregion
    }

    public class Tpo_FileUpLoad
    {
        public Tpo_FileUpLoad()
        {
            fileName = "0932539248.jpg";
            typeFile = "png";


        }
        public Tpo_FileUpLoad(string fileName, string typeFile, byte[] legth)
        {
            this.fileName = fileName;
            this.typeFile = typeFile;

            this.legth = legth;
        }
        private string fileName;

        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }
        private string typeFile;

        public string TypeFile
        {
            get { return typeFile; }
            set { typeFile = value; }
        }
        private byte[] legth;

        public byte[] Length
        {
            get { return legth; }
            set { legth = value; }
        }

    }
    public class Source
    {
        public const string obj_class_active = "class='active'";

        public const string obj_True = "True";
        public const string obj_A = "@dmins";
        public const string obj_Request_Page = "Page";
        public const string obj_Request_Respond = "Respond";

        public const string obj_Mes_Delcart = "Giỏ Hàng Thì Rỗng";
        public const string obj_Mes_HaveThisProduct = "Đã Có Mã Sản Phẩm Này";
        public const string obj_Mes_HaveThisUsername = "Đã Có Username Này";
        public const string obj_Mes_HaveThisEmail = "Đã Có Email Này";

        public const string obj_Mes_NotHaveThisProduct = "Không Có Mã Sản Phẩm Này";
        public const string obj_Mes_PassWrong = "Mật khẩu cũ không đúng";
        public const string obj_Mes_ChooseCateVN = "Chưa Chọn Danh Mục";
        public const string obj_Mes_ChooseLevel = "- - - - - - - - Choose Level {0} - - - - - - - -";
        public const string obj_Mes_SuccessPaymentCart = "Mua Hàng Thành Công Chúng Tôi Sẽ Liên Hệ Với Bạn Trong Thời Gian Sớm Nhất..";
        public const string obj_Mes_ErrorPaymentCart = "Mua Hàng Thất Bại Xin Vui Lòng Vào Giỏ Hàng Và Nhập Lại Thông Tin Chính Xác 1 Lần Nữa";
        public const string obj_Mes_ChooseCate = "Choose One Category";
        public const string obj_Mes_DelNotAllow = "Không Thể Xóa Item Này Vì Đã Được Sử Dụng";
        public const string obj_Mes_SuccessInsertCate = "Insert Success";
        public const string obj_Mes_DateNotinvalid = "Date End > Date Start";
        public const string obj_Mes_SuccessUpdate = "Update Success";
        public const string obj_Shoppingcart = "ShoppingCart";
        public const string obj_Account = "Account";
        public const string obj_role = "Role";
        public const string obj_Cateid = "Cateid";
        public const string obj_Zero = "0";
        public const string obj_AmOne = "-1";
        public const string obj_BillFirst = "00001";
        public const string obj_Accountname = "Accountname";
        public const string obj_lbltitle = "lbltitle";
        public const string obj_lblpageorder = "lblpageorder";
        public const string obj_Upload = "Upload";
        public const string obj_Result_Null = "";
        public const string obj_Result_Key = "Key";
        public const string obj_Result_KeyPrice = "KeyPrice";
        public const string obj_idprojects = "idprojects";


        public const string obj_Result_EditQuantityByProductID = "EditQuantityByProductID";
        public const string obj_Result_DeleteByProductID = "DeleteByProductID";
        public const string obj_Result_EmptyCart = "EmptCart";
        public const string obj_Result_Deletecart = "deletecart";
        public const string obj_Result_SuccessPaymentCart = "SuccessPaymentCart";
        public const string obj_Result_ErrorPaymentCart = "ErrorPaymentCart";
        public const string obj_Result_DelNotAllow = "DelNotAllow";
        public const string obj_Result_SuccessInsertCate = "Thêm thành công";
        public const string obj_Result_SuccessUpdate = "SuccessUpdateCate";
        public const string mes_mailsuccess = "Gửi Mail Thành Công,Chúng Tôi Sẽ Trả Lời Bạn Trong Thời Gian Sớm Nhất,KTS Chân Thành Cảm Ơn";
        public const string mes_fail = "Gửi Mail Không Thành Công,KTS Đang Trong Tình Trạng Bảo Trì,Hẹn Quý Khách Lần Sau";
        public const string mes_notvaliadcapcha = "Mã Bảo Mật Không Hợp Lệ";
        public const string obj_col_CategoryID = "CategoryID";
        public const string obj_col_ProductID = "ProductID";
        public const string obj_col_Price = "Price";
        public const string obj_col_Quantity = "Quantity";
        public const string obj_col_Total = "Total";
        public const string obj_col_ImagePhoto = "ImagePhoto";
        public const string obj_col_Detail = "Detail";
        public const string obj_col_ProductName = "ProductName";
        public const string obj_col_Description = "Description";
        public const string obj_col_CategoryNews_promotion = "promotion";
        public const string obj_col_CategoryNews_news = "news";
        public const string obj_col_CategoryNews_salesupport = "salesupport";
        public const string obj_col_CategoryGenaral_aboutus = "aboutus";
        public const string obj_col_CategoryGenaral_policy = "policy";
        public const string obj_col_CategoryGenaral_warranty = "warranty";
        public const string obj_vnd = "{0:0,0 vnđ}";
        public const string obj_nonevnd = "{0:0,0}";

        public const string obj_Appsetting_MenuSize = "MenuSize";
        public const string obj_Appsetting_PageSizeNew = "PageSizeNew";
        public const string obj_Appsetting_PageSizeDefault = "PageSizeDefault";

        public const string obj_Page_Message = "Message.aspx";
        public const string obj_Page_ProductList = "ProductList.aspx";
        public const string obj_Page_DetailProduct = "DetailProduct.aspx";
        public const string obj_Page_News = "News.aspx";
        public const string obj_Page_Default = "Default.aspx";
        public const string obj_Page_giohang = "giohang.aspx";
        public const string obj_Page_UpdateQuantity = "UpdateQuantity.aspx";
        public const string obj_Page_Payment = "Payment.aspx";
        public const string obj_Page_Search = "Search.aspx";
        public const string obj_Page_Login = "Login.aspx";
    }
}
